import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from "@nestjs/common";
import { Logger } from "@/common/log4js/log4j.util";
import { InjectRepository } from "@nestjs/typeorm";
import { Log } from "@/modules/log/entities/log.entity";
import { Repository } from "typeorm";
import { argumentsToString } from "@/common/utils/common";


@Catch()
export class ExceptionsFilter implements ExceptionFilter {
    constructor(
        @InjectRepository(Log)
        private readonly logRepository: Repository<Log>
    ) {
    }
    
    catch(exception: any, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const response = ctx.getResponse();
        const request = ctx.getRequest();
        const status = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
        const logFormat = `-----------------------------------------------------------------------
      Request original url: ${request.originalUrl}
      Method: ${request.method}
      IP: ${request.ip}
      Status code: ${status}
      Response: ${exception}
      -----------------------------------------------------------------------
      `;
        console.log("走了exceptions-filter.ts");
        Logger.error(logFormat);
        this.logRepository.save({
            ip: request.ip,
            userFlag: request?.user?.username || request.headers?.code,
            name: "服务器错误",
            method: request.method,
            message: exception.message,
            arguments: argumentsToString(request), // (request.body || request.params || request.query),
            status,
            path: request.originalUrl,
            type: 0
        });
        response.status(status).json({
            code: status,
            msg: `Service Error: ${exception}`
            // error: `${exception}`,
        });
    }
}
